<?php

namespace app\common\model\merchant;

use app\common\loader\ModelMerchant;
use app\common\model\BaseModel;
use think\Exception;

/**
 * 系统角色
 * Class MerchantRoles
 * @package app\common\model\merchant
 */
class MerchantRolesModel extends BaseModel
{
    //
    protected $name = 'merchant_roles';

    // 设置字段信息
    protected $schema = [
        'id' => 'int',        //
        'mer_id' => 'string',        // 所属商户,0系统创建,不可删除
        'title' => 'string',        // 角色名称
        'data_permission' => 'int',        // 数据权限(0:全部,1:部门及下属,2:个人)
        'description' => 'string',        // 角色描述
        'is_sys' => 'int',        // 是否系统创建  1 系统创建 0商户创建
        'op_user' => 'int',        // 操作人
        'create_at' => 'datetime',        // 创建时间
        'update_at' => 'datetime',        // 更新时间
    ];

    /**
     * 创建默认角色
     * @param array $param
     * @param string $merId 商户ID
     * @return int|string
     */
    public function createDefaultRole(array $param, string $merId)
    {

        $defaultData = [
            'mer_id' => $merId,
            'title' => '管理员',
            'data_permission' => 0,
            'is_sys' => 1,
            'op_user' => $param['op_user'],
            'create_at' => $param['create_at']
        ];
        return $this->db()->insertGetId($defaultData);
    }

    /**
     * 权限组添加修改
     * @param array $data
     * @return int|string
     * @throws Exception
     */
    public function addEdit(array $data)
    {
        $groupPermissionModel = ModelMerchant::MerchantRolesActions();
        try {
            $this->startTrans();

            $roleId = !empty($data["id"]) ? $data["id"] : 0;
            $menus = $data["menus"] ?? [];
            unset($data["id"], $data["menus"]);
            if ($roleId > 0) {
                $this->removeOption()->where("id", $roleId)->update(null, $data);
                $groupPermissionModel->where("role_id", $roleId)->delete();
            } else {
                $roleId = $this->insertGetId($data);
            }

            //获取所有选中选择菜单ID
            $menuIds = [];
            foreach ($menus as $menu) {
                foreach ($menu['actions'] as $menuId) {
                    $menuIds[] = $menuId;
                }
            }
            if(empty($menuIds)){
                throw new Exception('请选择角色权限',API_ERROR);
            }
            // 获取菜单列表,用于处理没有功能的菜单
            $menuList = ModelMerchant::MerchantSystemApi()->where("id", "in", $menuIds)->column(null, "page_action", 'id');
            //循环选中菜单及权限，重新生成请求权限，并插入权限组和权限的关联表中
            $groupPermission = [];
            foreach ($menus as $row) {
                foreach ($row["actions"] as $menuId) {
                    $groupPermission[] = [
                        "role_id" => $roleId,
                        "menu_id" => $row["id"],
                        "action_method" => $menuList[$menuId]
                    ];
                }
            }

            if (empty($groupPermission)) {
                api_exception(400, '未选择有效权限！请检查看重新提交');
            }
            $groupPermissionModel->insertAll($groupPermission);
            $this->commit();
            return $roleId;
        } catch (Exception $e) {
            $this->rollback();
            throw $e;
        }

    }
}
